<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-2xl mx-auto">
      <h2 class="text-2xl font-bold mb-6">物流跟踪</h2>
      <div class="bg-white rounded-lg shadow p-6">
        <div class="mb-4 pb-4 border-b">
          <p class="text-gray-500">物流号：{{ tracking.traceNo }}</p>
          <p class="text-primary font-medium mt-2">物流状态：{{ tracking.end === 1 ? '已签收' : '运输中' }}</p>
        </div>

        <el-timeline v-if="tracking.trace">
          <el-timeline-item
              v-for="(trace, index) in JSON.parse(tracking.trace)?.reverse() || []"
              :key="index"
              :timestamp="formattedTime(trace.time)"
          >
            {{ trace.desc }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {useRoute} from 'vue-router'
import {getTracking} from '@/api/orders'
import {ElMessage} from 'element-plus'

const route = useRoute()
const tracking = ref({
  orderNo: '',
  status: '',
  traces: []
})

// 使用计算属性处理时间戳
const formattedTime = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const fetchTracking = async () => {
  try {
    const {orderNo} = route.query
    const {data} = await getTracking(orderNo)
    tracking.value = data
  } catch (error) {
    ElMessage.error(error.message)
  }
}

onMounted(() => {
  fetchTracking()
})
</script>

<style scoped>
/* 时间线样式优化 */
:deep(.el-timeline-item__node--normal) {
  left: -1px;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 20px;
}

.tracking-item {
  padding: 4px 0;
}

/* 移动端优化 */
@media (max-width: 640px) {
  :deep(.el-timeline-item__timestamp) {
    font-size: 12px;
  }

  .tracking-item {
    font-size: 14px;
  }
}
</style>
